package com.xhsj.user.hr.system.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.xhsj.user.hr.base.BaseParam;
import com.xhsj.user.hr.process.dto.hrInterviewRegistration.TbHrInterviewRegistrationLanguageDto;
import com.xhsj.user.hr.process.hrEntryProcess.entity.TbHrApprovalEntryApply;
import com.xhsj.user.hr.process.hrEntryProcess.service.TbHrApprovalEntryApplyService;
import com.xhsj.user.hr.process.hrInterviewRegistration.query.TbHrInterviewRegistrationLanguageQuery;
import com.xhsj.user.hr.process.processDefinition.query.MapQuery;
import com.xhsj.user.hr.system.dto.UserInfoToAppDto;
import com.xhsj.user.hr.system.vo.UserInfoToAppVo;
import com.xhsj.user.hr.userInfo.mapper.TbGlobalUserDetailMapper;
import com.xhsj.user.security.entity.LoginUser;
import com.xhsj.user.hr.system.dto.UpdateUserDetailDto;
import com.xhsj.user.hr.system.dto.UserListDto;
import com.xhsj.user.hr.system.entity.TbGlobalMenu;
import com.xhsj.user.hr.system.entity.TbGlobalRole;
import com.xhsj.user.hr.system.entity.UserRole;
import com.xhsj.user.hr.system.mapper.TbGlobalRoleMapper;
import com.xhsj.user.hr.system.entity.TbGlobalUser;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xhsj.user.hr.system.query.LoadUserInfoQuery;
import com.xhsj.user.hr.system.query.UserBaseQuery;
import com.xhsj.user.hr.system.query.UserDetailQuery;
import com.xhsj.user.hr.system.query.UserListQuery;
import com.xhsj.user.hr.system.vo.FindUserListVo;
import com.xhsj.user.hr.system.vo.GetUserInfoByIdVo;
import com.xhsj.user.hr.system.vo.GetUserLoginInfoVo;
import com.xhsj.user.hr.userInfo.entity.*;
import com.xhsj.user.hr.userInfo.query.*;
import com.xhsj.user.hr.userInfo.service.*;
import com.xhsj.user.utils.StringUtils;
import com.xhsj.user.utils.UserUtils;
import lombok.Data;
import net.bytebuddy.implementation.bind.annotation.This;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.io.Serializable;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author suxl
 * @since Aug 27, 2020 10:39:27 AM
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
//@CacheConfig(cacheNames = "TbGlobalUser")
public class TbGlobalUserService extends ServiceImpl<TbGlobalUserMapper, TbGlobalUser> {
    @Autowired
    private TbGlobalUserMapper dao;

    @Autowired
    private TbGlobalMenuService tbGlobalMenuService;

    @Autowired
    private TbGlobalRoleMapper tbGlobalRoleMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    // 用户-合同信息表 服务实现类
    @Autowired
    private TbGlobalUserContractService tbGlobalUserContractService;

    // 用户_工作经历 服务实现类
    @Autowired
    private TbGlobalUserWorkService tbGlobalUserWorkService;

    // 用户_教育经历 服务实现类
    @Autowired
    private TbGlobalUserEducationService tbGlobalUserEducationService;

    // 用户_家庭情况 服务实现类
    @Autowired
    private TbGlobalUserFamilyService tbGlobalUserFamilyService;

    // 用户_语言关联表 服务实现类
    @Autowired
    private TbGlobalUserLanguageService tbGlobalUserLanguageService;

    // 用户_培训经历 服务实现类
    @Autowired
    private TbGlobalUserTrainService tbGlobalUserTrainService;

    // 用户_详细信息 服务实现类
    @Autowired
    private TbGlobalUserDetailService tbGlobalUserDetailService;

    // 用户_详细信息 服务实现类
    @Autowired
    private TbGlobalUserDetailMapper tbGlobalUserDetailMapper;

    // hr流程-入职申请表 服务实现类
    @Autowired
    private TbHrApprovalEntryApplyService tbHrApprovalEntryApplyService;

    // 用户_相关文件 服务实现类
    @Autowired
    private TbGlobalUserFileService tbGlobalUserFileService;

    @Value("${default.password}")
    private String pwd;

	/**
	 * 保存
	 * @author suxl
	 * @date Aug 27, 2020 10:39:27 AM
	 */
    //@CacheEvict(cacheNames="TbGlobalUser", allEntries=true)
    public boolean saveUser(TbGlobalUser entity) throws Exception {

        this.saveOrUpdateUser(entity);
        //删除用户角色
        this.delUserRole(entity.getUserId());

        List<Long> roleIds = entity.getRoleIds();
        List<UserRole> userRoles = Lists.newArrayList();
        for (Long roleId : roleIds) {
            UserRole userRole = new UserRole();
            userRole.setUserId(entity.getUserId());
            userRole.setRoleId(roleId);
            userRoles.add(userRole);
        }
        this.saveUserRole(userRoles);

        return true;

    }

    /**
     * 保存用户角色
     * @author 苏小林
     * @date 2020/9/1 13:34
     * @param: userRoles
     */
    private void saveUserRole(List<UserRole> userRoles) {
        dao.saveUserRole(userRoles);
    }

    /**
     * 删除用户角色
     * @author 苏小林
     * @date 2020/9/1 13:34
     * @param: userId
     */
    private void delUserRole(Long userId) {
        dao.delUserRole(userId);
    }

    private void saveOrUpdateUser(TbGlobalUser entity) throws Exception {
        // 手机号
        String phoneNumber = entity.getPhoneNumber();
        String oldOPhoneNumber = entity.getOldOPhoneNumber();
        if (StringUtils.isBlank(entity.getUserId()) || (StringUtils.isNotBlank(oldOPhoneNumber) && !oldOPhoneNumber.equals(phoneNumber))) {
            TbGlobalUser byPhoneNumber = dao.findByPhoneNumber(phoneNumber);
            if (byPhoneNumber != null) {
                throw new Exception("手机号重复");
            }
        }

        // 工号校验
        Long workNum = entity.getWorkNum();
        TbGlobalUser byWorkNum = dao.findByWorkNum(workNum);
           if (byWorkNum != null)
                if(!byWorkNum.getUserId().equals(entity.getUserId()) )
                throw new Exception("工号重复");

        entity.setUserName(entity.getPhoneNumber());
        if (StringUtils.isBlank(entity.getUserId())) {
            entity.setCreateDate(entity.getCreateDate()==null?new Date():entity.getCreateDate());
            entity.setUpdateDate(entity.getUpdateDate()==null?new Date():entity.getUpdateDate());
            entity.setUpdateBy(entity.getUpdateBy()==null?entity.getCreateBy():entity.getUpdateBy());
            entity.setDelFlag(0);
            entity.setPassword(bCryptPasswordEncoder.encode(pwd));// 设置初始密码
            int insert = dao.insert(entity);
            if (insert == 0) {
                log.error("新增影响行数为0");
                throw new Exception("新增影响行数为0");
            }
        } else {
            entity.setUpdateDate(new Date());
            entity.setUpdateBy(entity.getUpdateBy()==null?entity.getCreateBy():entity.getUpdateBy());
            entity.setCreateBy(null);
            int i = dao.updateById(entity);
            if (i == 0) {
                log.error("修改影响行数为0");
                throw new Exception("修改影响行数为0");
            }
        }
    }

    /**
	 * 通过id获取数据
	 * @author suxl
	 * @date Aug 27, 2020 10:39:27 AM
	 */
    @Override
    //@Cacheable(key = "#id",sync = true)
    public TbGlobalUser getById(Serializable id) {
        return super.getById(id);
    }

	/**
	 * 通过id删除数据
	 * @author suxl
	 * @date Aug 27, 2020 10:39:27 AM
	 */
    @Override
    //@CacheEvict(cacheNames="TbGlobalUser", allEntries=true)
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

	/**
	 * 批量删除数据
	 * @author suxl
	 * @date Aug 27, 2020 10:39:27 AM
	 */
    //@CacheEvict(cacheNames="SysDict", allEntries=true)
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        return super.removeByIds(idList);
    }

	/**
	 * 分页查询数据
	 * @author suxl
	 * @date Aug 27, 2020 10:39:27 AM
	 */
    //@Cacheable(key = "#data",sync = true)
    public IPage<FindUserListVo> selectPage(BaseParam baseParam) {

        Page<TbGlobalUser> page = new Page(baseParam.getPage(),baseParam.getSize());

        return dao.findList(page,baseParam.getName());
    }


    public LoginUser findByPhoneNumber(String username) {
        //根据用户名查询用户
        TbGlobalUser user = dao.findByPhoneNumber(username);
        if (user ==null){
            //后台抛出的异常是：org.springframework.security.authentication.BadCredentialsException: Bad credentials  坏的凭证 如果要抛出UsernameNotFoundException 用户找不到异常则需要自定义重新它的异常
            log.info("登录用户：" + username + " 不存在.");
            return null;
        }else{

            LoginUser loginUser = this.findUserRoleMenu(user);
            return loginUser;
        }
    }

    private LoginUser findUserRoleMenu(TbGlobalUser user) {
//        LoginUser loginUser = UserDtoMapper.INSTANCE.toLoginUser(user);

        Set<TbGlobalRole> sysRoles = tbGlobalRoleMapper.getRoleByUserId(user.getUserId());
        boolean flag = false;
        // 判断当前用户角色是不是超级管理员
        for (TbGlobalRole sysRole : sysRoles) {
            if (sysRole.getRoleId() == 1) {
                flag = true;
                break;
            }
        }
        Set<String> roleKeynames = sysRoles.parallelStream().map(TbGlobalRole::getRoleKeyname).collect(Collectors.toSet());

        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(user,loginUser);
        loginUser.setUsername(user.getUserName());
        loginUser.setSysRoles(roleKeynames);// 设置角色
        if (flag) {// 超级管理员
            // 查询权限列表
            QueryWrapper<TbGlobalMenu> wrapper = new QueryWrapper<>();
            wrapper.eq("menu_type",1);// 权限
            List<TbGlobalMenu> list = tbGlobalMenuService.list(wrapper);
            Set<String> permissions = list.parallelStream().map(TbGlobalMenu::getPerms)
                    .collect(Collectors.toSet());
            loginUser.setPermissions(permissions);// 设置权限集合
            return loginUser;
        }
        //查询权限集合
        Set<Long> roleIds = sysRoles.parallelStream().map(TbGlobalRole::getRoleId).collect(Collectors.toSet());
        if (!CollectionUtils.isEmpty(sysRoles)) {
            Set<TbGlobalMenu> sysPermissions= tbGlobalMenuService.getPermissionByRoleIds(roleIds);
            if (!CollectionUtils.isEmpty(sysPermissions)) {
                Set<String> permissions = sysPermissions.parallelStream().map(TbGlobalMenu::getPerms)
                        .collect(Collectors.toSet());
                loginUser.setPermissions(permissions);// 设置权限集合
            }
        }
        return loginUser;
    }

    public GetUserLoginInfoVo getUserLoginInfo(Long userId) {
        return dao.getUserLoginInfo(userId);
    }

    /**
     * 查询所有用户
     * @author 苏小林
     * @date 2020/9/1 14:39
     * @return: java.util.List<com.xhsj.user.hr.process.processDefinition.vo.MapQuery>
     */
    public List<MapQuery> getAllUsers() {
        return dao.getAllUsers();
    }

    /**
     * 通过id获取用户信息
     * @author 苏小林
     * @date 2020/9/1 16:13
     * @param: id
     * @return: com.xhsj.user.hr.system.vo.GetUserInfoByIdVo
     */
    public GetUserInfoByIdVo getUserInfoById(String id) {
        GetUserInfoByIdVo userInfoById = dao.getUserInfoById(id);
        if (userInfoById != null) {
            Long userId = userInfoById.getUserId();
            List<Long> roleIds = dao.getRoleIdsByUserId(userId);
            userInfoById.setRoleIds(roleIds);
        }
        return userInfoById;
    }

    /**
     * 通过id删除用户
     * @param id
     */
    public void deleteById(Long id) {
        super.removeById(id);
        this.delUserRole(id);
    }

    /**
     * 人员列表
     * @author liuqinghua
     * @date Sep 8, 2020 3:02:09 PM
     */
    public IPage<UserListQuery> getUserList(UserListDto data) {
        Page<UserListQuery> page = new Page<>(data.getPage(),data.getSize());
        return dao.getUserList(page,data);
    }

    /**
     * 我的人员列表
     * @author liuqinghua
     * @date Sep 8, 2020 3:02:09 PM
     */
    public List<UserListQuery> getMyUserList(UserListDto data) {
        LoginUser loginAppUser = UserUtils.getLoginAppUser();
        Long userId = loginAppUser.getUserId();
        return dao.getMyUserList(userId,data);
    }


    public UserInfoToAppDto getDetailUserInfoToApp(Long userId) {
        UserInfoToAppDto userInfoToAppDto = dao.getDetailUserInfoToApp(userId);

        return userInfoToAppDto;
    }

    /**
     * 人员详细信息
     * @author liuqinghua
     * @date Sep 8, 2020 3:02:09 PM
     */
    public UserDetailQuery getUserDetail(Long userId) {
        UserDetailQuery userDetailQuery = new UserDetailQuery();
        // 用户基本信息
        UserBaseQuery userBaseQuery = dao.getUserBaseQuery(userId);
        if (userBaseQuery != null) {
            userDetailQuery.setUserInfo(userBaseQuery);
        // 用户入职合同
        List<ContractListQuery> contractList = tbGlobalUserContractService.getContractList(userId);
        // 用户教育经历
        List<UserDetailEducationQuery> educationList = tbGlobalUserEducationService.getEducationList(userId);
        // 用户家庭信息
        List<UserDetailFamilyQuery> familyList = tbGlobalUserFamilyService.getFamilyList(userId);
        // 用户培训经历
        List<UserDetailTrainQuery> trainList = tbGlobalUserTrainService.getTrainList(userId);
         // 用户详细信息
//        UserDetailBaseQuery userDetailBaseQuery = tbGlobalUserDetailService.getUserDetailBaseQuery(userId);
        // 用户工作经历
        List<UserDetailWorkQuery> workList = tbGlobalUserWorkService.getWorkList(userId);
        // 语言
        List<UserDetailLanguageQuery> languageList = tbGlobalUserLanguageService.getLanguageList(userId);
            TbHrInterviewRegistrationLanguageQuery userDetailLanguageQuery = new TbHrInterviewRegistrationLanguageQuery();
            List<Long> dictIdQuery = new ArrayList<>();
            List<String> languageQuery =  new ArrayList<>();
            for (UserDetailLanguageQuery language: languageList) {
                dictIdQuery.add(language.getDictId());
                languageQuery.add(language.getLanguage());
            }
            userDetailLanguageQuery.setDictId(dictIdQuery);
            userDetailLanguageQuery.setLanguage(languageQuery);

        // 用户相关文件
       List<UserDetailFileQuery> fileInfo = tbGlobalUserFileService.getFileInfo(userId);
            userDetailQuery.setFileList(fileInfo);
            userDetailQuery.setContractList(contractList);
            userDetailQuery.setEducationList(educationList);
            userDetailQuery.setFamilyList(familyList);
            userDetailQuery.setTrainList(trainList);
            userDetailQuery.setWorkList(workList);
            userDetailQuery.setLanguageList(userDetailLanguageQuery);
        }
        return userDetailQuery;
    }

    public void deleteDataByUserId(Long userId) throws Exception {
        // 修改教育背景
        tbGlobalUserEducationService.deleteDataByUserId(userId);
        // 用户家庭成员
        tbGlobalUserFamilyService.deleteDataByUserId(userId);
        // 用户培训经历
        tbGlobalUserTrainService.deleteDataByUserId(userId);
        // 用户工作记录
        tbGlobalUserWorkService.deleteDataByUserId(userId);
        // 用户相关文件
        tbGlobalUserFileService.deleteDataByUserId(userId);
        // 删除语言
        tbGlobalUserLanguageService.deleteDataByUserId(userId);
    }
    /**
     * 人员修改
     * @author liuqinghua
     * @date Sep 8, 2020 3:02:09 PM
     */
    public void updateUserDetail(UpdateUserDetailDto data) throws Exception {
        UserBaseQuery userList = data.getApply();
        TbGlobalUser tbGlobalUser = new TbGlobalUser();
        BeanUtils.copyProperties(userList,tbGlobalUser);
        Long userId = tbGlobalUser.getUserId();
        TbGlobalUserDetail tbGlobalUserDetail = new TbGlobalUserDetail();
        BeanUtils.copyProperties(userList,tbGlobalUserDetail);
        // 删除相关的数据
        this.deleteDataByUserId(userId);
        // 修改用户基本信息
        if (tbGlobalUserDetail.getIsPeriod()!= null) {
        if (tbGlobalUserDetail.getIsPeriod() == 1 ) {
            tbGlobalUser.setJobStatus(1);
        }
        }
        // 校验手机号+校验银行卡号+校验身份证号
        String phoneNumber = userList.getPhoneNumber();
        String idCard = userList.getIdCard();
        String bankAccount = userList.getBankAccount();

        List<Long> userIdList = dao.getByPhoneNumber(phoneNumber);
        List<Long> idCardList = tbGlobalUserDetailMapper.getByIdCard(idCard);
        List<Long> bankAccountList = tbGlobalUserDetailMapper.getByBankAccount(bankAccount);

        if (userIdList.size() == 1) {
            // 如果相同 表示没有修改
            if (!userIdList.contains(tbGlobalUser.getUserId())) {
                throw new Exception("手机号码已经存在,请更换!");
            }
        }else if(userIdList.size() > 1)
            throw new Exception("手机号码已经存在,请更换!");

        if (idCardList.size()  == 1) {
            // 如果相同 表示没有修改
            if (!idCardList.contains(tbGlobalUserDetail.getUserId())) {
                throw new Exception("身份证号已经存在,请更换!");
            }
        } else if (idCardList.size()  > 1)
            throw new Exception("身份证号已经存在,请更换!");

        if (bankAccountList.size()  == 1) {
            // 如果相同 表示没有修改
            if (!bankAccountList.contains(tbGlobalUserDetail.getUserId())) {
                throw new Exception("银行号已经存在,请更换!");
            }
        } else if (bankAccountList.size()  > 1)
                throw new Exception("银行号已经存在,请更换!");

        if (!super.updateById(tbGlobalUser)) {
            throw new Exception("修改用户基本信息异常");
        }
        // 修改用户详细信息
        // 入职日期
        Date arrivalDate = tbGlobalUserDetail.getArrivalDate();
        // 试用期期限
        if (tbGlobalUserDetail.getSubmitStauts() == 1) {
            Integer probationPeriod = tbGlobalUserDetail.getProbationPeriod();
            if ("0".equals(String.valueOf(tbGlobalUserDetail.getIsPeriod())) && arrivalDate != null && probationPeriod != null) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(arrivalDate);
                calendar.add(Calendar.MONTH, probationPeriod);
                calendar.add(Calendar.DAY_OF_MONTH, -1);


//            long time = arrivalDate.getTime();
//            probationPeriod = probationPeriod*24*60*60*1000;
//            time+=probationPeriod;
//            // 转正日期
//            Date date = new Date(time);
                Date date = calendar.getTime();
                tbGlobalUserDetail.setPositiveDate(date);
            }
            if ("1".equals(String.valueOf(tbGlobalUserDetail.getIsPeriod()))) {
                tbGlobalUserDetail.setPositiveDate(arrivalDate);
            }
        }

        if (!tbGlobalUserDetailService.save(tbGlobalUserDetail)) {
            throw new Exception("修改用户详细信息异常");
        }
        // 修改合同信息
        TbGlobalUserContract tbGlobalUserContract = new TbGlobalUserContract();

    //   用户相关文件
            List<TbGlobalUserFile> fileList = data.getFileList();
            for (TbGlobalUserFile file: fileList) {
                file.setUserId(userId);
                file.setId(null);
                if (!tbGlobalUserFileService.save(file)) {
                    throw new Exception("用户相关文件信息异常");
                }
                if (file.getFileType() == 3) {
                    tbGlobalUserContract.setDelUrl(file.getDelUrl());
                    tbGlobalUserContract.setFileName(file.getFileName());
                    tbGlobalUserContract.setFileUrl(file.getFileUrl());
                }
            }
        BeanUtils.copyProperties(userList,tbGlobalUserContract);
        tbGlobalUserContract.setUserId(userList.getUserId());
        tbGlobalUserContract.setId(userList.getContractId());
        tbGlobalUserContract.setDictId(userList.getContratType());
        if (!tbGlobalUserContractService.save(tbGlobalUserContract)) {
            throw new Exception("修改合同信息异常");
        }
        // 修改薪资信息
        tbHrApprovalEntryApplyService.saveSalary(userId,tbGlobalUserDetail.getSalary(),tbGlobalUserDetail.getIsPeriod());
        // 修改教育背景
        List<TbGlobalUserEducation> educationList = data.getEducationList();
        for (TbGlobalUserEducation education: educationList) {
            education.setUserId(userId);
            education.setId(null);
            if (!tbGlobalUserEducationService.save(education)) {
                throw new Exception("修改教育背景信息异常");
            }
        }
        // 用户家庭成员
        List<TbGlobalUserFamily> familyList = data.getFamilyList();
        for (TbGlobalUserFamily family: familyList) {
            family.setUserId(userId);
            family.setId(null);
            if (!tbGlobalUserFamilyService.save(family)) {
                throw new Exception("用户家庭成员信息异常");
            }
        }
        // 用户培训经历
        List<TbGlobalUserTrain> trainList = data.getTrainList();
        for (TbGlobalUserTrain train: trainList) {
            train.setUserId(userId);
            train.setId(null);
            if (!tbGlobalUserTrainService.save(train)) {
                throw new Exception("用户培训经历信息异常");
            }
        }

       // 用户工作记录
        List<TbGlobalUserWork> workList = data.getWorkList();
        for (TbGlobalUserWork work: workList) {
            work.setUserId(userId);
            work.setId(null);
            if (!tbGlobalUserWorkService.save(work)) {
                throw new Exception("用户工作记录信息异常");
            }
        }


        // 修改用户语言
        TbHrInterviewRegistrationLanguageDto language = data.getLanguageList();
        List<String> languageNameList = language.getLanguage();
        List<Long> dictIdList = language.getDictId();
        for (String languageName: languageNameList) {
            int languageInt = languageNameList.indexOf(languageName);
            TbGlobalUserLanguage tbGlobalUserLanguage = new TbGlobalUserLanguage();
            tbGlobalUserLanguage.setUserId(userId);
            tbGlobalUserLanguage.setLanguage(languageName);
            for (Long dictId: dictIdList) {
                int dictInt = dictIdList.indexOf(dictId);
                if (languageInt == dictInt) {
                    tbGlobalUserLanguage.setDictId(dictId);
                    if (!tbGlobalUserLanguageService.save(tbGlobalUserLanguage)) {
                        throw new Exception("修改用户语言异常");
                    }
                    break;
                }

            }
        }


    }

    /**
     * 查询用户部门职位信息
     * @author 苏小林
     * @date 2020/9/9 9:24
     * @param: userId
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     */
    public Map<String, Object> getUserDeptAndPosition(Long userId) {
        return dao.getUserDeptAndPosition(userId);
    }

    /**
     * 获取用户基本信息 用于调岗： 部门 职位 上级领导 薪资
     * @return
     */
    public LoadUserInfoQuery loadUserInfo(Long userId) {
        return dao.loadUserInfo(userId);
    }

    /**
     * 查询在职人员统计
     * @author 苏小林
     * @date 2020/9/14 18:22
     * @param: date
     * @return: java.util.List<java.util.Map>
     */
    public List<Map> findInServiceStaff(String date) throws ParseException {
        Date currentDate = new Date();
        if (StringUtils.isNotBlank(date)) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            currentDate = simpleDateFormat.parse(date);
        }

        return dao.findInServiceStaff(currentDate);
    }

    /**
     * 通过角色id列表查询用户列表
     * @param roleIds
     * @return
     */
    public List<Long> getUserListByRoleIds(List<Long> roleIds) {
        return dao.getUserListByRoleIds(roleIds);
    }

    /**
     * 人事允许转正
     * @author liuqinghua
     * @date Sep 8, 2020 3:02:09 PM
     */
    public void becomeRegularButton(Long userId) throws Exception {

        TbGlobalUser tbGlobalUser = new TbGlobalUser();
        tbGlobalUser.setUserId(userId);
        tbGlobalUser.setJobStatus(2);
        if (dao.updateById(tbGlobalUser) != 1) {
            throw new Exception("人事允许转正异常");
        }
    }

    // 通过权限获取用户
    public List<Long> getUserIdByPrem(String perms) {
     return dao.getUserIdByPrem(perms);
    }

    /**
     * @Description:  获取所有员工
     * @Param:  无
     * @return:com.xhsj.user.hr.process.processDefinition.query.MapQuery
     * @Author: liuqinghua
     * @Date: 2020/11/10
     */
    public List<MapQuery> getOnTheJobEmployees() {
        return dao.getOnTheJobEmployees();
    }

    /**
     * @Description:  获取所有在职员工
     * @Param:  无
     * @return:com.xhsj.user.hr.process.processDefinition.query.MapQuery
     * @Author: liuqinghua
     * @Date: 2020/11/23
     */
    public List<Long> getOnTheJobEmployeesUserId() {
        return dao.getOnTheJobEmployeesUserId();
    }

    /**
     * 查询用户的领导
     * @author 苏小林
     * @date 2020/3/17 10:41
     * @param: i
     * @return: java.lang.String
     */
    public String getLeaderByUserId(Long userId) {
        QueryWrapper<TbGlobalUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("leader,status");
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("status",0);
        String leader= "";
        Map<String,Object> one = this.getMap(queryWrapper);
        if (one != null && "0".equals(String.valueOf(one.get("status")))) {
            leader = String.valueOf(one.get("leader"));
        }

        return leader;
    }

    /**
     * 通过用户id获取角色列表
     * @author 苏小林
     * @date 2020/3/17 11:46
     * @param: l
     * @return: java.util.List<java.lang.String>
     */
    public List<String> getRoleListByUserId(long userId) {
        List<String> list = dao.getRoleListByUserId(userId);
        return list;
    }

    //根据角色名得到角色id
    public List<String> getRoleListByRoleName(String roleName) {
        return  dao.getRoleListByRoleName(roleName);
    }

    // 根据角色id查用户名
    public String getFullNameByRoleId(String roleId) {
        return dao.getFullNameByRoleId(roleId);
    }

    // 根据用户id查用户名
    public String getFullNameByUserId(String userId) {
        return dao.getFullNameByUserId(userId);
    }

    public List<String> getDeptLeader(String deptId) {

        // 通过部门id查询职位列表
        List<Map<String,Object>> list = dao.getPositionId(deptId);

        String oneId = "11"; // 总经理
        String twoId = "12"; // 副总经理
        String positionId = "";// 职位id
        for (Map<String, Object> map : list) {
            // 如果parentId 为 11 则取 id 如果parentId 为 12 则取12
            String parentId = String.valueOf(map.get("parentId"));
            if (parentId.equals(oneId)) {
                String id = String.valueOf(map.get("id"));
                positionId = id;
                break;
            } else {
                positionId = twoId;
            }

        }

        List<String> userIds = dao.getUserIdByPostionId(positionId);
        if ("17".equals(positionId)) {
            Iterator<String> iterator = userIds.iterator();
            while (iterator.hasNext()) {
                String next = iterator.next();
                if (!"290".equals(next)) {
                    iterator.remove();
                }
            }
        }


        return userIds;
    }

    //得到编写文件得人员的角色是否是采购经理
    public boolean getCgManager(String proposerId,String roleKeyname) {
        String cgManager = dao.getCgManager(proposerId,roleKeyname);
        if(StringUtils.isNotBlank(cgManager)){
            return true;
        }
        return false;
    }

    // 获取用户信息根据用户id
    public List<TbGlobalUser> getByIds(List recipientList) {
        return dao.getByIds(recipientList);
    }

    /**
     * 查询用户信息给App
     * @author 苏小林
     * @date 2021/4/7 15:17
     */
    public UserInfoToAppVo getUserInfoToApp() {
        Long userId = UserUtils.getLoginAppUser().getUserId();

        UserInfoToAppVo userInfoToAppVo = dao.getUserInfoToApp(userId);

        return userInfoToAppVo;

    }

    public Long getLeaderId(Long toLong) {
       return dao.getLeaderId(toLong);
    }

    public void checkUserId(Object proposerId) throws Exception {
        String fullNameByUserId = this.getFullNameByUserId(String.valueOf(proposerId));
        if(StringUtils.isBlank(fullNameByUserId))
            throw new Exception("该条数据申请者已不存在，不能继续下一步");
    }

    public void checkRoleUserId(String roleKeyName,String roleName) throws Exception {
        List<Long> userIdByRoleName = dao.getUserIdByRoleName(roleKeyName);
        if(userIdByRoleName == null || userIdByRoleName.size() == 0)
            throw new Exception(roleName+"该角色下无用户");
    }

    public List<Long> checkRole(String rolekeyname, String roleName) throws Exception {
        List<String> roleListByRoleName = dao.getRoleListByRoleName(rolekeyname);
        if (roleListByRoleName !=null && roleListByRoleName.size() == 0) {
            throw new Exception(roleName+"不存在,请联系管理员添加相关人员");
        }
        List<Long> collect = roleListByRoleName.stream().map(r -> Long.valueOf(r)).collect(Collectors.toList());
        return collect;
    }


}
